import json
from django.http import JsonResponse
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from rest_framework.response import Response
from concurrent.futures import ThreadPoolExecutor, as_completed
from django.core.cache import cache
from django.db import transaction
from django.db.models import Q
from django.utils import timezone
from datetime import datetime

# 导入必要的模型和序列化器
from merchants.models import *
from vouchers.models import *
from cashbonus.models import *
from equity_mall.utils.pages import MyPage
from equity_mall.utils.wash_level1 import ylx_api
from equity_admin.tasks import *


class PushData(ModelViewSet):
    DISTRIBUTION_PLATFORM_CACHE_KEY = 'distribution_ids'
    DEFAULT_START_DATE = '2025-01-01 00:00:00'
    PROVIDENCE_ID = 7330

    def push(self, request):
        # 定义需要获取的数据列表
        data_futures = {}
        with ThreadPoolExecutor(max_workers=6) as executor:
            # 提交任务到线程池
            data_futures['ali_dai_jin_quan'] = executor.submit(self.action_ali_coupon_wechat_meituan_activity_data,1)   #支付宝
            # data_futures['weixin'] = executor.submit(self.action_ali_coupon_wechat_meituan_activity_data,2)             #微信
            # data_futures['shangjia'] = executor.submit(self.action_ali_coupon_wechat_meituan_activity_data,3)           #商户
            # data_futures['meituan'] = executor.submit(self.action_ali_coupon_wechat_meituan_activity_data,5)            #美团
            # data_futures['merchant_draw'] = executor.submit(self.merchant_eight_eight_activity_data)                      #商户达标奖励
            # data_futures['action_ash_activity'] = executor.submit(self.action_ash_activity)                             #微邮惠礼包



        # 收集所有任务的结果
        results = {}
        for future_name, future in data_futures.items():
            try:
                results[future_name] = future.result()
            except Exception as e:
                results[future_name] = f"Error: {str(e)}"

        return Response(results)

    @classmethod
    def process_activity_data(cls, queryset, log_model, api_method, activity_id_field='id'):
        """处理活动数据的通用方法"""
        success_count = 0
        for instance in queryset:
            # 验证instance是否有level属性
            if not hasattr(instance, 'level') or not hasattr(instance.level, 'account_nine'):
                print(f"Warning: Instance {instance} has no valid level or account_nine")
                continue

            # 准备推送数据
            push_data = {
                'sourceId': cls._get_activity_id(instance),
                'pushEventIds': cls._get_push_event_ids(instance),
                'orgNo': instance.level.account_nine,
                'activityName': cls._get_activity_name(instance),
                'startTime': cls._get_start_time(instance),
                'endTime': cls._get_end_time(instance)
            }

            # 验证必要字段
            if not push_data['sourceId']:
                print(f"Warning: No valid sourceId for instance {instance}, class: {instance.__class__.__name__}")
                continue

            if not push_data['startTime'] or not push_data['endTime']:
                print(f"Warning: Invalid time range for instance {instance}")
                continue

            # 检查是否已推送
            if log_model.objects.filter(activity_id=getattr(instance, activity_id_field)).exists():
                continue

            # 调用API并记录结果
            try:
                result = ylx_api(api_method, push_data)
                success = result['meta']['code'] == 200
                log_data = {
                    'activity_id': getattr(instance, activity_id_field),
                    'push_status': 1 if success else 2,
                    'push_time': timezone.now(),
                    'return_msg': result['meta']['msg'] if not success else ''
                }
                with transaction.atomic():
                    log_model.objects.update_or_create(
                        activity_id=getattr(instance, activity_id_field),
                        defaults=log_data
                    )
                success_count += 1 if success else 0
            except Exception as e:
                print(f"Error processing instance {instance}: {str(e)}")
                # 可以添加更详细的错误日志记录

        return success_count

    @classmethod
    def _get_activity_id(cls, instance):
        """安全获取活动ID，优先使用template_id"""
        # 尝试按优先级获取ID
        if hasattr(instance, 'template_id'):
            return instance.template_id
        if hasattr(instance, 'activity_id'):
            return instance.activity_id
        return None

    @classmethod
    def _get_push_event_ids(cls, instance):
        """安全获取pushEventIds"""
        value = str(getattr(instance, 'pushEventIds', ''))
        return value.split('|') if value else []

    @classmethod
    def _get_activity_name(cls, instance):
        """安全获取活动名称"""
        return getattr(instance, 'activity_name', getattr(instance, 'name', 'Unnamed Activity'))

    @classmethod
    def _get_start_time(cls, instance):
        """安全获取开始时间"""
        # 按优先级获取开始时间字段
        for attr in ['activity_start_time', 'publish_start_time', 'available_begin_time']:
            if hasattr(instance, attr):
                value = getattr(instance, attr)
                if value:  # 确保值不是None或空
                    return cls._format_datetime(value)
        return ''

    @classmethod
    def _get_end_time(cls, instance):
        """安全获取结束时间"""
        # 按优先级获取结束时间字段
        for attr in ['activity_end_time', 'publish_end_time', 'available_end_time']:
            if hasattr(instance, attr):
                value = getattr(instance, attr)
                if value:  # 确保值不是None或空
                    return cls._format_datetime(value)
        return ''

    @classmethod
    def _format_datetime(cls, dt):
        """格式化日期时间为API所需格式"""
        if not dt:
            return ''
        try:
            return dt.strftime("%Y-%m-%dT%H:%M:%S.120+08:00")
        except AttributeError:
            print(f"Warning: Invalid datetime format for {dt}")
            return ''



    @classmethod
    def action_ash_activity(cls):
        """处理-微邮惠礼包-活动"""
        cash_activities = CashActivity.objects.filter(
            available_begin_time__gte=cls.DEFAULT_START_DATE,
            level__prov_id=cls.PROVIDENCE_ID
        )
        #
        return cls.process_activity_data(
            cash_activities,
            CashActivityKeGuanLog,
            'ThirdActInfoSyncGdCrm'
        )

    @classmethod
    def merchant_eight_eight_activity_data(cls):
        """商户达标奖励"""
        merchant_activities = MerchantEightEightActivity.objects.filter(
            activity_start_time__gte=cls.DEFAULT_START_DATE,
            level__prov_id=cls.PROVIDENCE_ID
        )

        return cls.process_activity_data(
            merchant_activities,
            MerchantEightEightActivityKeGuanLog,
            'ThirdActInfoSyncGdCrm'
        )

    @classmethod
    def action_ali_coupon_wechat_meituan_activity_data(cls, coupon_channel=''):
        """支付宝、微信、商家、支付宝-处理推送活动"""
        distribution_ids = cls.get_distribution_platform()
        alidiscountcoupons = AliDiscountCoupon.objects.filter(
            publish_start_time__gte=cls.DEFAULT_START_DATE,
            coupon_channel=coupon_channel,
            level__prov_id=cls.PROVIDENCE_ID,
        ).exclude(distribution_platform__id__in=distribution_ids)
        return cls.process_activity_data(
            alidiscountcoupons,
            AliDiscountActivityCouponInfoKeGuanLog,
            'ThirdActInfoSyncGdCrm',
            activity_id_field='id'
        )

    @classmethod
    def get_distribution_platform(cls):
        """找出去除对应的平台后的派发id"""
        distribution_ids = cache.get(cls.DISTRIBUTION_PLATFORM_CACHE_KEY)
        if distribution_ids is not None:
            return distribution_ids

        platform_names = ["微邮惠", "邮乐享", "(安徽)皖邮惠", "(江苏)江苏邮政微金融",
                          "(吉林)吉林邮政E权益", "(陕西)陕邮惠小程序", "(广西)邮储好礼汇"]
        ids = []

        for platform_name in platform_names:
            platform_ids = AliDiscountCouponDistributionPlatform.objects.filter(
                platform_name=platform_name
            ).values_list("id", flat=True)

            if platform_ids:
                ids.append(platform_ids[0])

        cache.set(cls.DISTRIBUTION_PLATFORM_CACHE_KEY, ids)
        return ids